package com.boot.mall.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.common.utils.R;
import com.boot.mall.ware.feign.MemberFeignService;
import com.boot.mall.ware.vo.MemberAddressVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.common.utils.PageUtils;
import com.boot.common.utils.Query;

import com.boot.mall.ware.dao.WareInfoDao;
import com.boot.mall.ware.entity.WareInfoEntity;
import com.boot.mall.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils pageWare(Map<String, Object> params) {
        String key = (String) params.get("key");
        long current = Integer.parseInt(params.get("page").toString());
        long limit = Integer.parseInt(params.get("limit").toString());
        QueryWrapper<WareInfoEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            queryWrapper.eq("id",key)
                    .or().like("name",key)
                    .or().like("address",key)
                    .or().like("areacode",key);
        }
        Page<WareInfoEntity> page = new Page<>(current,limit);
        this.page(page,queryWrapper);
        // 结果封装
        PageUtils pageUtils = new PageUtils(page.getRecords(),(int)page.getTotal(),(int)page.getSize(),(int)current);
        return pageUtils;
    }

    /**
     * 根据收货地址计算运费
     * @param addrId
     * @return
     */
    @Override
    public BigDecimal getAddressFare(Long addrId) {
        ObjectMapper mapper = new ObjectMapper();
        // 远程查询当前地址信息
        R res = memberFeignService.getAddress(addrId);
        Object object = res.get("memberReceiveAddress");
        MemberAddressVo address = mapper.convertValue(object,MemberAddressVo.class);
        String substring = address.getPostCode().substring(0, 2);
        return new BigDecimal(substring);
    }
}